package com.itheima.网络编程.udp2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class 服务端 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        new Thread(() -> {
            while (true) {
                try {
                    DatagramSocket ds = new DatagramSocket(10001);
                    byte[] bys = new byte[1024 * 1024];
                    DatagramPacket dgp = new DatagramPacket(bys, bys.length);
                    synchronized (服务端.class) {
                        ds.receive(dgp);
                        System.out.println("服务端接收到的数据:");
                        System.out.println(new String(dgp.getData(), 0, dgp.getLength()));
                        ds.close();
                        System.out.println("=====================================================");
                    }
                } catch (IOException e) {
                    System.out.println("服务端接收线程异常..................");
                }

            }
        }).start();

        new Thread(() -> {
            while (true) {
                try {
                    DatagramSocket ds1 = new DatagramSocket();
                    synchronized (String.class) {
                        //System.out.println("服务端请输入要发给客户端的数据:");
                        byte[] bys1 = sc.next().getBytes();
                        DatagramPacket dgp1 = new DatagramPacket(bys1, bys1.length, InetAddress.getByName("192.168.2.23"), 10002);
                        ds1.send(dgp1);
                        ds1.close();
                    }
                    System.out.println("=====================================================");

                } catch (IOException e) {
                    System.out.println("客户端发送线程异常..................");
                }

            }
        }).start();


    }
}
